<template>
    <div class="dashboard-container">
      <el-row :gutter="20">
        <!-- 数据概览卡片 -->
        <el-col :span="6" v-for="(item, index) in statisticsData" :key="index">
          <el-card class="statistics-card" shadow="hover">
            <div class="statistics-card-content">
              <div class="statistics-icon" :style="{backgroundColor: item.color}">
                <el-icon><component :is="item.icon" /></el-icon>
              </div>
              <div class="statistics-info">
                <div class="statistics-value">{{ item.value }}</div>
                <div class="statistics-title">{{ item.title }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
  
      <el-row :gutter="20" class="chart-row">
        <!-- 销售趋势图 -->
        <el-col :span="16">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>销售趋势</span>
                <el-radio-group v-model="timeRange" size="small">
                  <el-radio-button label="week">本周</el-radio-button>
                  <el-radio-button label="month">本月</el-radio-button>
                  <el-radio-button label="year">全年</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="salesChartRef">
              <div id="salesChart" style="width: 100%; height: 100%"></div>
            </div>
          </el-card>
        </el-col>
  
        <!-- 畅销商品 -->
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>畅销商品排行</span>
                <el-button text>查看更多</el-button>
              </div>
            </template>
            <div class="hot-products">
              <div v-for="(product, index) in hotProducts" :key="index" class="hot-product-item">
                <div class="hot-product-rank">{{ index + 1 }}</div>
                <el-image class="hot-product-image" :src="getImageUrl(product.image)" fit="cover"></el-image>
                <div class="hot-product-info">
                  <div class="hot-product-name">{{ product.name }}</div>
                  <div class="hot-product-sales">销量: {{ product.sales }}</div>
                </div>
                <div class="hot-product-price">¥{{ product.price }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
  
      <el-row :gutter="20" class="chart-row">
        <!-- 最新订单 -->
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>最新订单</span>
                <el-button text @click="$router.push('/orders')">查看更多</el-button>
              </div>
            </template>
            <el-table :data="latestOrders" style="width: 100%" border>
              <el-table-column prop="id" label="订单号" width="180" />
              <el-table-column prop="user" label="用户" width="120" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="scope">
                  ¥{{ scope.row.amount }}
                </template>
              </el-table-column>
              <el-table-column prop="time" label="下单时间" width="180" />
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag :type="getOrderStatusType(getStatusText(scope.row.status))">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="viewOrder(scope.row.id)">
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import request from '../api/index'
  import * as echarts from 'echarts'
  
  const router = useRouter()
  const timeRange = ref('month')
  const loading = ref(false)
  const salesChartRef = ref(null)
  let salesChart = null
  
  // 统计卡片数据
  const statisticsData = reactive([
    { title: '总销售额', value: '¥0', icon: 'Money', color: '#409EFF' },
    { title: '订单总数', value: '0', icon: 'List', color: '#67C23A' },
    { title: '用户总数', value: '0', icon: 'User', color: '#E6A23C' },
    { title: '商品总数', value: '0', icon: 'ShoppingBag', color: '#F56C6C' }
  ])
  
  // 热销商品
  const hotProducts = ref([])
  
  // 最新订单
  const latestOrders = ref([])
  
  // 订单状态对应的标签类型
  const getOrderStatusType = (status) => {
    const typeMap = {
      '待付款': 'warning',
      '已付款': 'info',
      '待发货': 'info',
      '已发货': 'primary',
      '已完成': 'success',
      '已取消': 'danger'
    }
    return typeMap[status] || 'info'
  }
  
  // 获取状态文本
  const getStatusText = (status) => {
    const map = {
      // 中文状态映射（保持不变）
      '待付款': '待付款',
      '已付款': '已付款',
      '待发货': '待发货',
      '已发货': '已发货',
      '已完成': '已完成',
      '已取消': '已取消',
      '已退款': '已退款',
      // 英文状态映射
      'pending': '待付款',
      'paid': '已付款',
      'shipped': '已发货',
      'completed': '已完成',
      'cancelled': '已取消',
      'refunded': '已退款'
    }
    return map[status] || status
  }
  
  // 查看订单详情
  const viewOrder = (orderId) => {
    router.push(`/orders/${orderId}`)
  }
  
  // 添加处理图片URL的函数
  const getImageUrl = (image) => {
    if (!image) return '';
    
    // 检查是否已经是完整的URL
    if (image.startsWith('http')) return image;
    
    // 服务器基础URL
    const serverBaseUrl = 'http://localhost:5000';
    
    // 确保路径正确
    const path = image.startsWith('/') ? image : `/${image}`;
    
    // 如果是相对路径，添加uploads前缀
    if (!path.startsWith('/uploads') && !path.startsWith('/api')) {
      return `${serverBaseUrl}/uploads${path}`;
    }
    
    return `${serverBaseUrl}${path}`;
  }
  
  // 生成销售趋势图表的函数
  const renderSalesChart = () => {
    if (!salesChartRef.value) return;
    
    // 如果已存在图表实例，先销毁
    if (salesChart) {
      salesChart.dispose();
    }
    
    // 初始化图表
    salesChart = echarts.init(document.getElementById('salesChart'));
    
    // 模拟数据
    const days = [];
    const salesData = [];
    
    // 生成模拟数据
    if (timeRange.value === 'week') {
      const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      for (let i = 0; i < 7; i++) {
        days.push(weekDays[i]);
        salesData.push(Math.floor(Math.random() * 500) + 100);
      }
    } else if (timeRange.value === 'month') {
      for (let i = 1; i <= 30; i++) {
        days.push(`${i}日`);
        salesData.push(Math.floor(Math.random() * 500) + 100);
      }
    } else if (timeRange.value === 'year') {
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      for (let i = 0; i < 12; i++) {
        days.push(months[i]);
        salesData.push(Math.floor(Math.random() * 5000) + 1000);
      }
    }
    
    // 设置图表选项
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: days,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '销售额',
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#409EFF'
          },
          data: salesData
        }
      ]
    };
    
    // 设置图表
    salesChart.setOption(option);
  }
  
  // 监听时间范围变化
  const watchTimeRange = () => {
    renderSalesChart();
  }
  
  // 在timeRange变化时重新渲染图表
  watch(timeRange, () => {
    watchTimeRange();
  });
  
  // 浏览器窗口大小变化时，重绘图表
  const handleResize = () => {
    if (salesChart) {
      salesChart.resize();
    }
  }
  
  // 加载仪表盘数据
  const loadDashboardData = async () => {
    loading.value = true
    try {
      const res = await request({
        url: '/dashboard',
        method: 'get'
      })
      
      // 更新统计数据
      if (res.statistics) {
        statisticsData[0].value = `¥${res.statistics.totalSales.toLocaleString()}`
        statisticsData[1].value = res.statistics.totalOrders.toLocaleString()
        statisticsData[2].value = res.statistics.totalUsers.toLocaleString()
        statisticsData[3].value = res.statistics.totalProducts.toLocaleString()
      }
      
      // 更新热销商品
      if (res.hotProducts) {
        hotProducts.value = res.hotProducts
      }
      
      // 更新最新订单
      if (res.latestOrders) {
        latestOrders.value = res.latestOrders
      }
    } catch (error) {
      console.error('获取仪表盘数据失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  onMounted(() => {
    loadDashboardData()
    // 初始化渲染图表
    setTimeout(() => {
      renderSalesChart()
    }, 500)
    
    // 添加窗口大小变化事件监听
    window.addEventListener('resize', handleResize)
  })
  
  // 组件销毁前清除事件监听和图表实例
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (salesChart) {
      salesChart.dispose()
      salesChart = null
    }
  })
  </script>
  
  <style scoped>
  .dashboard-container {
    padding: 20px;
  }
  
  .statistics-card {
    margin-bottom: 20px;
  }
  
  .statistics-card-content {
    display: flex;
    align-items: center;
  }
  
  .statistics-icon {
    width: 50px;
    height: 50px;
    border-radius: 6px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 15px;
  }
  
  .statistics-icon .el-icon {
    font-size: 24px;
    color: #fff;
  }
  
  .statistics-info {
    flex: 1;
  }
  
  .statistics-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .statistics-title {
    font-size: 14px;
    color: #666;
  }
  
  .chart-row {
    margin-top: 20px;
  }
  
  .chart-card {
    height: 400px;
  }
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .chart-container {
    height: 325px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .chart-placeholder {
    color: #909399;
    font-size: 16px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .hot-products {
    height: 325px;
    overflow-y: auto;
  }
  
  .hot-product-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .hot-product-item:last-child {
    border-bottom: none;
  }
  
  .hot-product-rank {
    width: 24px;
    height: 24px;
    background-color: #f5f7fa;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
  }
  
  .hot-product-item:nth-child(1) .hot-product-rank {
    background-color: #f56c6c;
    color: #fff;
  }
  
  .hot-product-item:nth-child(2) .hot-product-rank {
    background-color: #e6a23c;
    color: #fff;
  }
  
  .hot-product-item:nth-child(3) .hot-product-rank {
    background-color: #409eff;
    color: #fff;
  }
  
  .hot-product-image {
    width: 50px;
    height: 50px;
    margin-right: 10px;
    border-radius: 4px;
  }
  
  .hot-product-info {
    flex: 1;
    overflow: hidden;
  }
  
  .hot-product-name {
    font-size: 14px;
    margin-bottom: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .hot-product-sales {
    font-size: 12px;
    color: #909399;
  }
  
  .hot-product-price {
    font-weight: bold;
    color: #f56c6c;
  }
  </style>